package com.cqs.leetcode.tree;

import com.cqs.leetcode.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lixiaowen
 * @create 2019-12-10
 */
public class ConstructBinaryTreefromInorderandPostorderTraversal106 {

    /**
     * @param inorder
     * @param postorder
     * @return
     */
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder == null || postorder == null || postorder.length != inorder.length || inorder.length <= 0) {
            return null;
        }
        Map<Integer, Integer> map = new HashMap<>(inorder.length);
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i],i);
        }
        return buildTree(0, inorder.length - 1, postorder, 0, postorder.length - 1, map);
    }



    public TreeNode buildTree(int il, int ir, int[] postorder, int pl, int pr, Map<Integer, Integer> map) {
        if(il > ir || (pl > pr)) return null;
        //求中序根节点的索引
        Integer index = map.get(postorder[pr]);
        TreeNode root = new TreeNode(postorder[pr]);
        //递归构建子树数
        root.left = buildTree(il, index - 1, postorder, pl, index + pr - ir -1, map);
        //递归构建右子树
        root.right = buildTree(index + 1 ,ir, postorder,  (index + pr - ir) ,pr - 1, map);
        return root;
    }
}
